package com.app.yourradioapp593.activities;

import static com.app.yourradioapp593.utils.Constant.LOCALHOST_ADDRESS;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.app.yourradioapp593.BuildConfig;
import com.app.yourradioapp593.Config;
import com.app.yourradioapp593.R;
import com.app.yourradioapp593.callbacks.CallbackSettings;
import com.app.yourradioapp593.database.prefs.AdsPref;
import com.app.yourradioapp593.database.prefs.SharedPref;
import com.app.yourradioapp593.models.App;
import com.app.yourradioapp593.models.Settings;
import com.app.yourradioapp593.rests.RestAdapter;
import com.app.yourradioapp593.utils.AdsManager;
import com.app.yourradioapp593.utils.Constant;
import com.app.yourradioapp593.utils.Tools;
import com.solodroidx.ads.appopen.AppOpenAd;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ActivitySplash extends AppCompatActivity {

    public static final String TAG = "ActivitySplash";
    ProgressBar progressBar;
    AdsPref adsPref;
    AdsManager adsManager;
    SharedPref sharedPref;
    ImageView imgSplash;
    Call<CallbackSettings> callbackCall = null;
    Settings ads;
    App app;
    boolean isForceOpenAds;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.getTheme(this);
        setContentView(R.layout.activity_splash);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root_view), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        Tools.windowLightStatusBar(this, false);
        isForceOpenAds = Config.FORCE_TO_SHOW_APP_OPEN_AD_ON_START;
        sharedPref = new SharedPref(this);

        adsPref = new AdsPref(this);
        adsManager = new AdsManager(this);

        imgSplash = findViewById(R.id.img_splash);
        if (sharedPref.getIsDarkTheme()) {
            imgSplash.setImageResource(R.drawable.bg_splash_dark);
        } else {
            imgSplash.setImageResource(R.drawable.bg_splash_default);
        }

        progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        Tools.postDelayed(this::requestConfig, Constant.DELAY_SPLASH);

    }

    @SuppressWarnings("ConstantConditions")
    private void requestConfig() {
        if (Config.SERVER_KEY.contains("XXXXX")) {
            new AlertDialog.Builder(this)
                    .setTitle("App not configured")
                    .setMessage("Please put your Server Key and Rest API Key from settings menu in your admin panel to AppConfig, you can see the documentation for more detailed instructions.")
                    .setPositiveButton(getString(R.string.option_ok), (dialogInterface, i) -> startMainActivity())
                    .setCancelable(false)
                    .show();
        } else {
            String decode = Tools.decodeBase64(Config.SERVER_KEY);
            String data = Tools.decrypt(decode);
            String[] results = data.split("_applicationId_");
            String apiUrl = results[0].replace("http://localhost", LOCALHOST_ADDRESS);
            String applicationId = results[1];
            sharedPref.saveConfig(apiUrl, applicationId);

            if (applicationId.equals(BuildConfig.APPLICATION_ID)) {
                if (Tools.isConnect(this)) {
                    requestAPI(apiUrl);
                } else {
                    startMainActivity();
                }
            } else {
                new AlertDialog.Builder(this)
                        .setTitle("Error")
                        .setMessage("Whoops! invalid server key or applicationId, please check your configuration")
                        .setPositiveButton(getString(R.string.option_ok), (dialog, which) -> finish())
                        .setCancelable(false)
                        .show();
            }
        }
    }

    private void requestAPI(String apiUrl) {
        this.callbackCall = RestAdapter.createAPI(apiUrl).getSettings(Config.REST_API_KEY, BuildConfig.APPLICATION_ID);
        this.callbackCall.enqueue(new Callback<>() {
            public void onResponse(@NonNull Call<CallbackSettings> call, @NonNull Response<CallbackSettings> response) {
                CallbackSettings resp = response.body();
                if (resp != null && resp.status.equals("ok")) {
                    ads = resp.settings;
                    app = resp.app;

                    adsPref.saveAds(
                            ads.ad_status.equals("on"),
                            ads.ad_type,
                            ads.backup_ads,
                            ads.admob_publisher_id,
                            ads.admob_app_id,
                            ads.admob_banner_unit_id,
                            ads.admob_interstitial_unit_id,
                            ads.admob_native_unit_id,
                            ads.admob_app_open_ad_unit_id,
                            ads.ad_manager_banner_unit_id,
                            ads.ad_manager_interstitial_unit_id,
                            ads.ad_manager_native_unit_id,
                            ads.ad_manager_app_open_ad_unit_id,
                            ads.fan_banner_unit_id,
                            ads.fan_interstitial_unit_id,
                            ads.fan_native_unit_id,
                            ads.startapp_app_id,
                            ads.unity_game_id,
                            ads.unity_banner_placement_id,
                            ads.unity_interstitial_placement_id,
                            ads.applovin_banner_ad_unit_id,
                            ads.applovin_interstitial_ad_unit_id,
                            ads.applovin_native_ad_manual_unit_id,
                            ads.applovin_app_open_ad_unit_id,
                            ads.applovin_banner_zone_id,
                            ads.applovin_banner_mrec_zone_id,
                            ads.applovin_interstitial_zone_id,
                            ads.ironsource_app_key,
                            ads.ironsource_banner_id,
                            ads.ironsource_interstitial_id,
                            ads.wortise_app_id,
                            ads.wortise_banner_unit_id,
                            ads.wortise_interstitial_unit_id,
                            ads.wortise_native_unit_id,
                            ads.wortise_app_open_unit_id,
                            ads.interstitial_ad_interval,
                            ads.native_ad_interval,
                            ads.native_ad_index
                    );

                    sharedPref.saveCredentials(
                            ads.fcm_notification_topic,
                            ads.onesignal_app_id,
                            ads.more_apps_url,
                            ads.privacy_policy
                    );

                    if (app.status != null && app.status.equals("0")) {
                        Intent intent = new Intent(getApplicationContext(), ActivityRedirect.class);
                        intent.putExtra("redirect_url", app.redirect_url);
                        startActivity(intent);
                        finish();
                        Log.d(TAG, "App is inactive, call redirect method");
                    } else {
                        showAppOpenAdIfAvailable();
                        Log.d(TAG, "App is active");
                    }
                    Log.d("ActivitySplash", "success load config");
                } else {
                    showAppOpenAdIfAvailable();
                }
            }

            public void onFailure(@NonNull Call<CallbackSettings> call, @NonNull Throwable th) {
                Log.e(TAG, "onFailure");
                showAppOpenAdIfAvailable();
            }
        });
    }

    private void showAppOpenAdIfAvailable() {
        if (isForceOpenAds) {
            if (Config.APP_OPEN_AD_ON_START) {
                adsManager.loadAppOpenAd(Config.APP_OPEN_AD_ON_START, true, () -> {
                    startMainActivity();
                    AppOpenAd.isAppOpenAdLoaded = false;
                    Log.d(TAG, "showAppOpenAdIfAvailable");
                });
            } else {
                startMainActivity();
                Log.d(TAG, "app open on start disabled");
            }
        } else {
            if (adsPref.getAdStatus() && Config.APP_OPEN_AD_ON_START) {
                Application application = getApplication();
                ((MyApplication) application).showAdIfAvailable(this, this::startMainActivity);
            } else {
                startMainActivity();
                Log.d(TAG, "startMainActivity");
            }
        }
    }

    private void startMainActivity() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppOpenAd.isAppOpenAdLoaded = false;
        Constant.isRadioPlaying = false;
    }

}
